package cn.anxingongyou.anxin.controller;

import cn.anxingongyou.anxin.entity.SignUp;
import cn.anxingongyou.anxin.entity.UserParent;
import cn.anxingongyou.anxin.entity.Wages;
import cn.anxingongyou.anxin.entity.Work;
import cn.anxingongyou.anxin.service.SignUpService;
import cn.anxingongyou.anxin.service.UserParentService;
import cn.anxingongyou.anxin.service.WagesService;
import cn.anxingongyou.anxin.service.WorkService;
import cn.anxingongyou.anxin.utils.Result;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class SignUpCcontroller {
    protected static final Logger logger = LoggerFactory.getLogger(SignUpCcontroller.class);
    private final SignUpService signUpService;
    private final UserParentService userParentService;
    private final WorkService workService;
    private final WagesService wagesService;
    @Autowired
    public SignUpCcontroller(SignUpService signUpService, UserParentService userParentService, WorkService workService, WagesService wagesService) {
        this.signUpService = signUpService;
        this.userParentService = userParentService;
        this.workService = workService;
        this.wagesService = wagesService;
    }

    @ApiOperation("添加报名信息")
    @ApiResponses({
            @ApiResponse(code = 201,message = "添加成功"),
            @ApiResponse(code = 500,message = "添加失败")
    })
    @RequestMapping(value = "/signup/add",method = RequestMethod.POST)
    public Map addSignUp(
            @RequestBody @ApiParam(value = "报名信息", required = true) SignUp signUp
            ){
        signUp.setCreated(new Date());
        signUp.setUpdated(new Date());
        int res = signUpService.insert(signUp);
        if(res > 0) {
            return Result.instance(201,"添加成功").toJsonMap();
        } else {
            return Result.instance(500,"添加失败").toJsonMap();
        }
    }

    @ApiOperation("api添加报名信息")
    @ApiResponses({
            @ApiResponse(code = 201,message = "添加成功"),
            @ApiResponse(code = 500,message = "添加失败")
    })
    @RequestMapping(value = "/api/signup/add",method = RequestMethod.POST)
    public Map apiAddSignUp(
            @RequestBody @ApiParam(value = "报名信息", required = true) SignUp signUp
    ){
        // 是否已经报过名
        SignUp signUp1 = new SignUp();
        signUp1.setUserPid(signUp.getUserPid());
        signUp1.setWorkId(signUp.getWorkId());
        SignUp signUp2 = signUpService.selectOne(signUp1);
        logger.info("222{}",signUp2);


        if(signUp2 == null){

            // 检查报名人数是否已经经满了

            int count = signUpService.countSignUpIsEmploy(signUp.getWorkId(), 1);
            logger.info("count{}",count);
            if(count < signUp.getWorkNumber()){
                //录取人数未满
                signUp.setCreated(new Date());
                signUp.setUpdated(new Date());
                int res = signUpService.insert(signUp);
                if(res > 0) {
                    return Result.instance(201,"报名成功").toJsonMap();
                } else {
                    return Result.instance(500,"报名失败").toJsonMap();
                }
            }else {
                // 录取人数已满
                return Result.instance(501,"录取人数已满").toJsonMap();
            }
        } else {
            return Result.instance(502,"已报名").toJsonMap();
        }
    }

    @ApiOperation("删除报名信息")
    @ApiResponses({
            @ApiResponse(code = 204,message = "删除成功"),
            @ApiResponse(code = 500,message = "删除失败")
    })
    @RequestMapping(value = "/signup/del/{id}",method = RequestMethod.GET)
    public Map delAdmin(
            @PathVariable @ApiParam(value = "报名主键", required = true) Long id
    ){
        int res = signUpService.deleteByPrimaryKey(id);
        if(res > 0) {
            return Result.instance(204,"删除成功").toJsonMap();
        } else {
            return Result.instance(500,"删除失败").toJsonMap();
        }
    }

    @ApiOperation("更新报名信息")
    @ApiResponses({
            @ApiResponse(code = 204,message = "更新成功"),
            @ApiResponse(code = 500,message = "更新失败")
    })
    @RequestMapping(value = "/signup/update",method = RequestMethod.POST)
    public Map updateSignUp(
            @RequestBody @ApiParam(value = "报名信息,必传主键", required = true) SignUp signUp
    ){
        int res = signUpService.updateByPrimaryKeySelective(signUp);
        if(res > 0) {
            return Result.instance(204,"更新成功").toJsonMap();
        } else {
            return Result.instance(500,"更新失败").toJsonMap();
        }

    }

    @ApiOperation("api招聘者拒绝录用")
    @ApiResponses({
            @ApiResponse(code = 204,message = "更新成功"),
            @ApiResponse(code = 500,message = "更新失败")
    })
    @RequestMapping(value = "/api/signup/unemployer",method = RequestMethod.POST)
    public Map apiSignUpodUnemployer(
            @RequestBody @ApiParam(value = "必传主键,工作主键,求职用户主键，雇主用户主键", required = true) SignUp signUp
    ){
        SignUp signUp1 = new SignUp();
        signUp1.setId(signUp.getId());
        signUp1.setIsEmployment(2);  // 0:未处理 1:录用 2:未录用 3:结束工作
        int res = signUpService.updateByPrimaryKeySelective(signUp1);
        if(res > 0) {
            return Result.instance(204,"拒绝录用成功").toJsonMap();
        } else {
            return Result.instance(500,"操作失败").toJsonMap();
        }
    }

    @ApiOperation("api招聘者结束工作")
    @ApiResponses({
            @ApiResponse(code = 204,message = "更新成功"),
            @ApiResponse(code = 500,message = "更新失败")
    })
    @RequestMapping(value = "/api/signup/finished/{id}",method = RequestMethod.GET)
    public Map apiSignUpFinished(
            @PathVariable("id") @ApiParam(value = "必传主键", required = true) Long id
    ){
        SignUp signUp1 = new SignUp();
        signUp1.setId(id);
        signUp1.setIsEmployment(3);  // 0:未处理 1:录用 2:未录用 3:结束工作
        int res = signUpService.updateByPrimaryKeySelective(signUp1);
        SignUp signUp = signUpService.selectOneByPrimaryKey(id);
        UserParent userParent = new UserParent();
        userParent.setId(signUp.getUserPid());
        userParent.setIsEmployment(0);
        userParentService.updateByPrimaryKeySelective(userParent);
        if(res > 0) {
            return Result.instance(204,"结束工作成功").toJsonMap();
        } else {
            return Result.instance(500,"操作失败").toJsonMap();
        }
    }

    @ApiOperation("api招聘者确认录用")
    @ApiResponses({
            @ApiResponse(code = 204,message = "更新成功"),
            @ApiResponse(code = 500,message = "更新失败")
    })
    @RequestMapping(value = "/api/signup/employment",method = RequestMethod.POST)
    public Map apiSignUpodEmployer(
            @RequestBody @ApiParam(value = "必传主键,工作主键,求职用户主键，雇主用户主键", required = true) SignUp signUp
    ){
        // 检查该用户是否被其他人录用
        UserParent userParent1 = userParentService.selectOneByPrimaryKey(signUp.getUserPid());
        logger.info("userparent:{}",userParent1);
        if(userParent1.getIsEmployment() == 1){
            // 已经被雇佣 不能在录用
            return Result.instance(500,"该用户已经被录用").toJsonMap();
        }
        // 更新报名表
        SignUp signUp1 = new SignUp();
        signUp1.setId(signUp.getId());
        signUp1.setIsEmployment(1);  // 0:未处理 1:录用 2:未录用 3:结束工作
        int res = signUpService.updateByPrimaryKeySelective(signUp1); // 将报名表的是否录用 更新为录用
        if(res > 0) {
        } else {
            return Result.instance(500,"更新报名为录用失败").toJsonMap();
        }
        // 更新用户表 标记用户已经被雇佣了  user_parent 的 is_employment和 work_id
        UserParent userParent = new UserParent();
        userParent.setId(signUp.getUserPid());
        userParent.setIsEmployment(1); //（0:未被雇佣 1:被雇佣）
        userParent.setWorkId(signUp.getWorkId());
        userParent.setSignUpId(signUp.getId());
        int userRes = userParentService.updateByPrimaryKeySelective(userParent);
        if(userRes > 0) {
        } else {
            return Result.instance(500,"更新user_parent标记用户已经被雇佣失败").toJsonMap();
        }
        //添加多条打卡记录
        Work work = workService.selectOneByPrimaryKey(signUp.getWorkId()); //获取工作信息
        int salary_type  = work.getSalaryType(); //0:元/小时 1:元/天 2:元/件

        List<Wages> wagesList = new ArrayList<>();
        if(salary_type == 0){
            // 元/小时
            long workStartDatestamp = work.getWorkStartDatestamp().getTime();
            long workEndDatestamp = work.getWorkEndDatestamp().getTime();
            while(workStartDatestamp < workEndDatestamp){
                Wages wages = new Wages();
                wages.setSignUpId(signUp.getId());
                wages.setWorkId(signUp.getWorkId());
                wages.setUserPid(signUp.getUserPid());
                wages.setUserWid(signUp.getUserPid());
                wages.setEmployerPid(signUp.getEmployerPid());
                wages.setEmployerEid(signUp.getEmployerPid());
                wages.setWorkStartDate(work.getWorkStartDate());
                wages.setWorkStartTime(work.getWorkStartTime());
                wages.setWorkStartDatestamp(work.getWorkStartDatestamp());
                wages.setWorkEndDate(work.getWorkEndDate());
                wages.setWorkEndTime(work.getWorkEndTime());
                wages.setWorkEndDatestamp(work.getWorkEndDatestamp());
                wages.setSignInDate(timestampToDateStr(workStartDatestamp));
                wages.setSettlement(work.getSettlement());
                wages.setSalary(work.getSalary());
                wages.setSalaryType(work.getSalaryType());
                wages.setWorkStrength(work.getWorkStrength());
                Float price = work.getSalary() * work.getWorkStrength();
                wages.setWorkerGetPrice(price.toString());
                // 添加手续费
                price += work.getPoundage();
                wages.setPayablePrice(price.toString());
                wages.setPaidPrice(price.toString());
                wages.setPayStatus(0);
                wages.setCreated(new Date());
                wages.setUpdated(new Date());
                wagesList.add(wages);
                workStartDatestamp = workStartDatestamp + 24*60*60*1000;
            }
            int wagesRes = wagesService.insertList(wagesList);
            if(wagesRes > 0) {
            } else {
                return Result.instance(500,"批量添加打卡记录失败").toJsonMap();
            }
        }else if(salary_type == 1) {
            // 元/天
            long workStartDatestamp = work.getWorkStartDatestamp().getTime();
            long workEndDatestamp = work.getWorkEndDatestamp().getTime();
            while(workStartDatestamp < workEndDatestamp){
                Wages wages = new Wages();
                wages.setSignUpId(signUp.getId());
                wages.setWorkId(signUp.getWorkId());
                wages.setUserPid(signUp.getUserPid());
                wages.setUserWid(signUp.getUserPid());
                wages.setEmployerPid(signUp.getEmployerPid());
                wages.setEmployerEid(signUp.getEmployerPid());
                wages.setWorkStartDate(work.getWorkStartDate());
                wages.setWorkStartTime(work.getWorkStartTime());
                wages.setWorkStartDatestamp(work.getWorkStartDatestamp());
                wages.setWorkEndDate(work.getWorkEndDate());
                wages.setWorkEndTime(work.getWorkEndTime());
                wages.setWorkEndDatestamp(work.getWorkEndDatestamp());
                wages.setSignInDate(timestampToDateStr(workStartDatestamp));
                wages.setSettlement(work.getSettlement());
                wages.setSalary(work.getSalary());
                wages.setSalaryType(work.getSalaryType());
                wages.setWorkStrength(work.getWorkStrength());

                Float price = work.getSalary();
                wages.setWorkerGetPrice(price.toString());
                // 添加手续费
                price += work.getPoundage();
                wages.setPayablePrice(price.toString());
                wages.setPaidPrice(price.toString());

                wages.setPayStatus(0);
                wages.setCreated(new Date());
                wages.setUpdated(new Date());
                wagesList.add(wages);
                workStartDatestamp = workStartDatestamp + 24*60*60*1000;
            }
            int wagesRes = wagesService.insertList(wagesList);
            if(wagesRes > 0) {
            } else {
                return Result.instance(500,"批量添加打卡记录失败").toJsonMap();
            }
        }else if(salary_type == 2){
            // 元/件
            long workStartDatestamp = work.getWorkStartDatestamp().getTime();
            Wages wages = new Wages();
            wages.setSignUpId(signUp.getId());
            wages.setWorkId(signUp.getWorkId());
            wages.setUserPid(signUp.getUserPid());
            wages.setUserWid(signUp.getUserPid());
            wages.setEmployerPid(signUp.getEmployerPid());
            wages.setEmployerEid(signUp.getEmployerPid());
            wages.setWorkStartDate(work.getWorkStartDate());
            wages.setWorkStartTime(work.getWorkStartTime());
            wages.setWorkStartDatestamp(work.getWorkStartDatestamp());
            wages.setWorkEndDate(work.getWorkEndDate());
            wages.setWorkEndTime(work.getWorkEndTime());
            wages.setWorkEndDatestamp(work.getWorkEndDatestamp());
            wages.setSignInDate(timestampToDateStr(workStartDatestamp));
            wages.setSettlement(work.getSettlement());
            wages.setSalary(work.getSalary());
            wages.setSalaryType(work.getSalaryType());
            wages.setWorkStrength(work.getWorkStrength());
            Float price = work.getSalary() * work.getWorkStrength();
            wages.setWorkerGetPrice(price.toString());
            // 添加手续费
            price += work.getPoundage();
            wages.setPayablePrice(price.toString());
            wages.setPaidPrice(price.toString());
            wages.setPayStatus(0);
            wages.setCreated(new Date());
            wages.setUpdated(new Date());

            int wagesRes = wagesService.insert(wages);
            if(wagesRes > 0) {
            } else {
                return Result.instance(500,"批量添加打卡记录失败").toJsonMap();
            }
        }

        return Result.instance(204,"录取成功").toJsonMap();
    }

    public String timestampToDateStr(long timestamp) {
        Date date = new Date(timestamp);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(date);
    }
    @ApiOperation("获取报名信息通过")
    @ApiResponses({
            @ApiResponse(code = 200,message = "获取成功"),
            @ApiResponse(code = 500,message = "获取失败")
    })
    @RequestMapping(value = "/signup/findBySignUp",method = RequestMethod.POST)
    public Map findOneAdmin(
            @RequestBody @ApiParam(value = "报名信息", required = true) SignUp signUp
    ){
        SignUp adminl = signUpService.selectOne(signUp);
        if(adminl != null) {
            return Result.<SignUp>instance(200,"获取成功",adminl).toJsonMap();
        } else {
            return Result.instance(500,"获取失败").toJsonMap();
        }
    }

    @ApiOperation("获取报名信息通过主键")
    @ApiResponses({
            @ApiResponse(code = 200,message = "获取成功"),
            @ApiResponse(code = 500,message = "获取失败")
    })
    @RequestMapping(value = "/signup/findOneById/{id}",method = RequestMethod.GET)
    public Map findOneById(
            @PathVariable @ApiParam(value = "报名主键", required = true) Long id
    ){
        SignUp adminl = signUpService.selectOneByPrimaryKey(id);
        if(adminl != null) {
            return Result.<SignUp>instance(200,"获取成功",adminl).toJsonMap();
        } else {
            return Result.instance(500,"获取失败").toJsonMap();
        }
    }

    @ApiOperation("api获取报名信息通过主键")
    @ApiResponses({
            @ApiResponse(code = 200,message = "获取成功"),
            @ApiResponse(code = 500,message = "获取失败")
    })
    @RequestMapping(value = "/api/signup/findOneById/{id}",method = RequestMethod.GET)
    public Map apiFindOneById(
            @PathVariable @ApiParam(value = "报名主键", required = true) Long id
    ){
        SignUp adminl = signUpService.selectOneByPrimaryKey(id);
        if(adminl != null) {
            return Result.<SignUp>instance(200,"获取成功",adminl).toJsonMap();
        } else {
            return Result.instance(500,"获取失败").toJsonMap();
        }
    }

    @ApiOperation("获取所有报名列表")
    @ApiResponses({
            @ApiResponse(code = 200,message = "查询成功"),
            @ApiResponse(code = 500,message = "查询失败")
    })
    @RequestMapping(value = "/signup/page/{pageNum}/{pageSize}",method = RequestMethod.POST)
    public Map selectAddressByAdmin(
            @PathVariable("pageNum") @ApiParam(value = "第几页", required = true) int pageNum,
            @PathVariable("pageSize") @ApiParam(value = "每页多少条", required = true) int pageSize,
            @RequestBody @ApiParam(value = "报名信息", required = true)  SignUp signUp){
        PageInfo<SignUp> pageInfo = signUpService.page(pageNum, pageSize, signUp);
        Map<String,Object> res = new HashMap<>();
        res.put("total", pageInfo.getTotal());
        res.put("pageNum", pageInfo.getPageNum());
        res.put("pageSize", pageInfo.getPageSize());
        res.put("list",pageInfo.getList());
        return Result.<Map>instance(200,"查询成功",res).toJsonMap();
    }

    @ApiOperation("api获取所有报名列表")
    @ApiResponses({
            @ApiResponse(code = 200,message = "查询成功"),
            @ApiResponse(code = 500,message = "查询失败")
    })
    @RequestMapping(value = "/api/signup/page/{pageNum}/{pageSize}",method = RequestMethod.POST)
    public Map apiSelectAddressByAdmin(
            @PathVariable("pageNum") @ApiParam(value = "第几页", required = true) int pageNum,
            @PathVariable("pageSize") @ApiParam(value = "每页多少条", required = true) int pageSize,
            @RequestBody @ApiParam(value = "报名信息", required = true)  SignUp signUp){
        PageInfo<SignUp> pageInfo = signUpService.page(pageNum, pageSize, signUp);
        Map<String,Object> res = new HashMap<>();
        res.put("total", pageInfo.getTotal());
        res.put("pageNum", pageInfo.getPageNum());
        res.put("pageSize", pageInfo.getPageSize());
        res.put("list",pageInfo.getList());
        return Result.<Map>instance(200,"查询成功",res).toJsonMap();
    }

}
